import { useState } from 'react';
import { Settings, Check, AlertCircle, FileDown } from 'lucide-react';
import { FileService } from '@/services';
import Button from '@/components/common/Button';
import FileUploader from '@/components/common/FileUploader';

interface VideoCompressorProps {
  onClose?: () => void;
}

const VideoCompressor: React.FC<VideoCompressorProps> = ({ onClose }) => {
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [compressionLevel, setCompressionLevel] = useState<'low' | 'medium' | 'high' | 'custom'>(
    'medium'
  );
  const [targetSize, setTargetSize] = useState<number | undefined>();
  const [crfValue, setCrfValue] = useState(23);
  const [preserveQuality, setPreserveQuality] = useState(true);
  const [isProcessing, setIsProcessing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [results, setResults] = useState<any[]>([]);

  const handleFilesSelected = (files: File[]) => {
    setSelectedFiles(files);
  };

  const handleCompress = async () => {
    if (selectedFiles.length === 0) return;

    setIsProcessing(true);
    setProgress(0);
    setResults([]);

    try {
      // Process parameters are handled by the backend service
      // format: 'mp4',
      // quality: crfValue,
      // bitrate: getBitrateFromCompressionLevel(),
      // resolution: undefined

      // 模拟压缩过程
      for (let i = 0; i < selectedFiles.length; i++) {
        const file = selectedFiles[i];
        const currentProgress = (i / selectedFiles.length) * 100;
        setProgress(currentProgress);

        // 在实际实现中，这里会调用 Tauri 后端
        await new Promise(resolve => setTimeout(resolve, 3000));

        const originalSize = file.size;
        const compressedSize = Math.round(originalSize * getCompressionRatio());

        setResults(prev => [
          ...prev,
          {
            id: i,
            fileName: file.name,
            status: 'completed',
            originalSize,
            compressedSize,
            compressionRatio: Math.round((1 - compressedSize / originalSize) * 100),
            duration: '3秒',
          },
        ]);

        setProgress(((i + 1) / selectedFiles.length) * 100);
      }

      setIsProcessing(false);
    } catch (error) {
      console.error('压缩失败:', error);
      setIsProcessing(false);
    }
  };

  // const getBitrateFromCompressionLevel = (): number | undefined => {
  //   switch (compressionLevel) {
  //     case 'low': return 4000;
  //     case 'medium': return 2000;
  //     case 'high': return 1000;
  //     case 'custom': return targetSize ? targetSize * 8 : undefined;
  //     default: return 2000;
  //   }
  // };

  const getCompressionRatio = (): number => {
    switch (compressionLevel) {
      case 'low':
        return 0.7;
      case 'medium':
        return 0.5;
      case 'high':
        return 0.3;
      case 'custom':
        return targetSize ? targetSize / (selectedFiles[0]?.size || 1) : 0.5;
      default:
        return 0.5;
    }
  };

  const compressionPresets = [
    {
      level: 'low',
      label: '轻度压缩',
      description: '画质几乎无损，文件大小减少约30%',
      color: 'text-green-600',
      bgColor: 'bg-green-50',
    },
    {
      level: 'medium',
      label: '标准压缩',
      description: '平衡画质和文件大小，减少约50%',
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
    },
    {
      level: 'high',
      label: '强力压缩',
      description: '文件大小大幅减小，画质有一定损失，减少约70%',
      color: 'text-orange-600',
      bgColor: 'bg-orange-50',
    },
    {
      level: 'custom',
      label: '自定义设置',
      description: '手动调整压缩参数',
      color: 'text-purple-600',
      bgColor: 'bg-purple-50',
    },
  ];

  return (
    <div className='max-w-6xl mx-auto p-6 space-y-8'>
      {/* Header */}
      <div className='flex items-center justify-between'>
        <div>
          <h1 className='text-3xl font-bold text-gray-900'>视频压缩</h1>
          <p className='text-gray-600 mt-2'>智能压缩视频文件，在保持画质的同时大幅减小文件大小</p>
        </div>
        <div className='flex gap-3'>
          <Button variant='secondary' onClick={onClose}>
            返回
          </Button>
        </div>
      </div>

      <div className='grid grid-cols-1 lg:grid-cols-3 gap-8'>
        {/* Left Panel - File Selection */}
        <div className='lg:col-span-2 space-y-6'>
          {/* File Upload */}
          <div className='card p-6'>
            <h2 className='text-xl font-semibold text-gray-900 mb-4'>选择视频文件</h2>
            <FileUploader
              maxFiles={10}
              accept='.mp4,.avi,.mov,.mkv,.wmv,.flv,.webm'
              onFilesSelected={handleFilesSelected}
            />

            {selectedFiles.length > 0 && (
              <div className='mt-4 space-y-3'>
                <h3 className='text-sm font-medium text-gray-900'>
                  文件详情 ({selectedFiles.length})
                </h3>
                {selectedFiles.map((file, index) => (
                  <div key={index} className='p-3 bg-gray-50 rounded-lg'>
                    <div className='flex items-center justify-between mb-2'>
                      <span className='text-sm font-medium text-gray-900 truncate'>
                        {file.name}
                      </span>
                      <span className='text-xs text-gray-500'>
                        {FileService.formatFileSize(file.size)}
                      </span>
                    </div>
                    <div className='text-xs text-gray-500 space-y-1'>
                      <div>
                        预计压缩后大小:{' '}
                        {FileService.formatFileSize(file.size * getCompressionRatio())}
                      </div>
                      <div>压缩率: {Math.round((1 - getCompressionRatio()) * 100)}%</div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Processing Section */}
          {isProcessing && (
            <div className='card p-6'>
              <h2 className='text-xl font-semibold text-gray-900 mb-4'>正在压缩...</h2>
              <div className='space-y-4'>
                <div className='flex items-center justify-between'>
                  <span className='text-sm text-gray-700'>整体进度</span>
                  <span className='text-sm font-medium text-blue-600'>{Math.round(progress)}%</span>
                </div>
                <div className='w-full bg-gray-200 rounded-full h-2'>
                  <div
                    className='bg-blue-600 h-2 rounded-full transition-all duration-300'
                    style={{ width: `${progress}%` }}
                  />
                </div>
              </div>
            </div>
          )}

          {/* Results Section */}
          {results.length > 0 && (
            <div className='card p-6'>
              <h2 className='text-xl font-semibold text-gray-900 mb-4'>压缩结果</h2>
              <div className='space-y-4'>
                {results.map(result => (
                  <div
                    key={result.id}
                    className='p-4 bg-green-50 border border-green-200 rounded-lg'
                  >
                    <div className='flex items-center justify-between mb-3'>
                      <div className='flex items-center gap-2'>
                        <Check className='w-5 h-5 text-green-600' />
                        <span className='text-sm font-medium text-gray-900'>{result.fileName}</span>
                      </div>
                      <span className='text-xs text-green-600 font-medium'>完成</span>
                    </div>

                    <div className='grid grid-cols-2 gap-4 text-sm'>
                      <div>
                        <span className='text-gray-500'>原始大小:</span>
                        <span className='ml-2 font-medium'>
                          {FileService.formatFileSize(result.originalSize)}
                        </span>
                      </div>
                      <div>
                        <span className='text-gray-500'>压缩后:</span>
                        <span className='ml-2 font-medium text-green-600'>
                          {FileService.formatFileSize(result.compressedSize)}
                        </span>
                      </div>
                      <div>
                        <span className='text-gray-500'>压缩率:</span>
                        <span className='ml-2 font-medium text-blue-600'>
                          {result.compressionRatio}%
                        </span>
                      </div>
                      <div>
                        <span className='text-gray-500'>处理时间:</span>
                        <span className='ml-2 font-medium'>{result.duration}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Right Panel - Settings */}
        <div className='space-y-6'>
          {/* Compression Settings */}
          <div className='card p-6'>
            <div className='flex items-center gap-2 mb-4'>
              <Settings className='w-5 h-5 text-gray-600' />
              <h3 className='text-lg font-semibold text-gray-900'>压缩设置</h3>
            </div>

            <div className='space-y-4'>
              {/* Compression Level */}
              <div>
                <label className='block text-sm font-medium text-gray-700 mb-3'>压缩级别</label>
                <div className='space-y-3'>
                  {compressionPresets.map(preset => (
                    <label
                      key={preset.level}
                      className={`flex items-start gap-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${
                        compressionLevel === preset.level
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 hover:border-gray-300'
                      }`}
                    >
                      <input
                        type='radio'
                        name='compressionLevel'
                        value={preset.level}
                        checked={compressionLevel === preset.level}
                        onChange={e => setCompressionLevel(e.target.value as any)}
                        className='mt-1 text-blue-600 focus:ring-blue-500'
                      />
                      <div className='flex-1'>
                        <div className='flex items-center gap-2'>
                          <span className={`font-medium ${preset.color}`}>{preset.label}</span>
                          {preset.level === 'medium' && (
                            <span className='text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full'>
                              推荐
                            </span>
                          )}
                        </div>
                        <p className='text-xs text-gray-500 mt-1'>{preset.description}</p>
                      </div>
                    </label>
                  ))}
                </div>
              </div>

              {/* Custom Settings */}
              {compressionLevel === 'custom' && (
                <div className='space-y-4 p-3 bg-gray-50 rounded-md'>
                  <div>
                    <label className='block text-sm font-medium text-gray-700 mb-2'>
                      目标文件大小 (MB)
                    </label>
                    <input
                      type='number'
                      value={targetSize || ''}
                      onChange={e =>
                        setTargetSize(e.target.value ? Number(e.target.value) : undefined)
                      }
                      placeholder='自动计算'
                      className='w-full p-2 border border-gray-300 rounded-md'
                    />
                  </div>

                  <div>
                    <label className='block text-sm font-medium text-gray-700 mb-2'>
                      CRF 值 (0-51)
                    </label>
                    <input
                      type='range'
                      min='0'
                      max='51'
                      value={crfValue}
                      onChange={e => setCrfValue(Number(e.target.value))}
                      className='w-full'
                    />
                    <div className='flex justify-between text-xs text-gray-500'>
                      <span>最佳质量</span>
                      <span>{crfValue}</span>
                      <span>最小文件</span>
                    </div>
                  </div>

                  <label className='flex items-center gap-2'>
                    <input
                      type='checkbox'
                      checked={preserveQuality}
                      onChange={e => setPreserveQuality(e.target.checked)}
                      className='rounded border-gray-300 text-blue-600 focus:ring-blue-500'
                    />
                    <span className='text-sm text-gray-700'>优先保持画质</span>
                  </label>
                </div>
              )}

              {/* Quality Warning */}
              {compressionLevel === 'high' && (
                <div className='flex items-center gap-2 p-3 bg-orange-50 border border-orange-200 rounded'>
                  <AlertCircle className='w-4 h-4 text-orange-600' />
                  <span className='text-sm text-orange-700'>
                    强力压缩会显著降低画质，建议先测试小文件
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Action Buttons */}
          <div className='card p-6'>
            <Button
              variant='primary'
              size='lg'
              icon={<FileDown className='w-5 h-5' />}
              onClick={handleCompress}
              disabled={selectedFiles.length === 0 || isProcessing}
              className='w-full justify-center'
            >
              {isProcessing ? '压缩中...' : '开始压缩'}
            </Button>

            <div className='mt-4 text-center text-sm text-gray-500'>
              {selectedFiles.length > 0 ? (
                <div>
                  <p>预计总大小减少: {Math.round((1 - getCompressionRatio()) * 100)}%</p>
                  <p className='text-xs mt-1'>
                    从{' '}
                    {FileService.formatFileSize(
                      selectedFiles.reduce((sum, file) => sum + file.size, 0)
                    )}
                    到{' '}
                    {FileService.formatFileSize(
                      selectedFiles.reduce(
                        (sum, file) => sum + file.size * getCompressionRatio(),
                        0
                      )
                    )}
                  </p>
                </div>
              ) : (
                <p>请先选择要压缩的视频文件</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideoCompressor;
